package com.qf.rbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.rbac.annotation.DataFilter;
import com.qf.rbac.shiro.ShiroConstants;
import com.qf.rbac.sys.entity.SysDept;
import com.qf.rbac.sys.entity.SysUser;
import com.qf.rbac.sys.mapper.SysUserMapper;
import com.qf.rbac.sys.service.ISysUserRoleService;
import com.qf.rbac.sys.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.rbac.utils.Constants;
import com.qf.rbac.utils.PageQueryUtil;
import com.qf.rbac.utils.PageVo;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    ISysUserRoleService sysUserRoleService;

    @Override
    @DataFilter
    public PageVo queryPage(Map<String, Object> params) {
        IPage<SysUser> page = new PageQueryUtil<SysUser>().getPage(params);
        String sql_filter = (String) params.get("sql_filter");
        final QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().apply(StringUtils.isNotBlank(sql_filter), sql_filter);
        this.page(page,queryWrapper);
        return new PageVo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(SysUser user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        String s = new SimpleHash(ShiroConstants.hashAlgorithmName, user.getPassword(), salt, ShiroConstants.hashIterations).toString();
        user.setPassword(s);
        this.save(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUser user) {
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(null);
        }else{
            SysUser userEntity = this.getById(user.getUserId());
            String s = new SimpleHash(ShiroConstants.hashAlgorithmName, user.getPassword(), user.getSalt(), ShiroConstants.hashIterations).toString();
            user.setPassword(s);
        }
        this.updateById(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }
}
